<template>
  <div class="repair-manage">
    <!-- 查询区域 -->
    <el-form :inline="true" :model="searchForm" class="search-form" @submit.prevent>
      <el-form-item label="报修编号">
        <el-input v-model="searchForm.repairId" placeholder="请输入报修编号" clearable />
      </el-form-item>
      <el-form-item label="设备编号">
        <el-input v-model="searchForm.deviceId" placeholder="请输入设备编号" clearable />
      </el-form-item>
      <!-- <el-form-item label="部门">
        <el-select v-model="searchForm.deptId" placeholder="请选择部门" clearable style="width: 200px;">
          <el-option 
            v-for="dept in deptList" 
            :key="dept.deptId" 
            :label="dept.deptName" 
            :value="dept.deptId" 
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="故障描述">
        <el-input v-model="searchForm.faultDescription" placeholder="请输入故障描述" clearable />
      </el-form-item>
      <el-form-item label="审核状态">
        <el-select v-model="searchForm.auditStatus" placeholder="请选择审核状态" clearable style="width: 100px;">
          <el-option label="待审核" :value="0" />
          <el-option label="已通过" :value="1" />
          <el-option label="已拒绝" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="报废状态">
        <el-select v-model="searchForm.isScrapped" placeholder="请选择报废状态" clearable style="width: 60px;">
          <el-option label="否" :value="false" />
          <el-option label="是" :value="true" />
        </el-select>
      </el-form-item>
      <el-form-item label="报废审核状态">
        <el-select v-model="searchForm.scrapAuditStatus" placeholder="请选择报废审核状态" clearable style="width: 100px;">
          <el-option label="待审核" :value="0" />
          <el-option label="已通过" :value="1" />
          <el-option label="已拒绝" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="searchForm.createTimeRange"
          type="daterange"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
      <el-form-item v-if="isOperator || isAdmin">
        <el-button type="success" @click="showAddDialog = true">新增报修</el-button>
      </el-form-item>
    </el-form>

    <!-- 报修列表 -->
    <el-table :data="repairList" border>
      <el-table-column prop="repairId" label="报修编号" min-width="80" />
      <el-table-column prop="deviceId" label="设备编号" min-width="80" />
      <el-table-column prop="deptName" label="部门" min-width="100" />
      <el-table-column prop="faultDescription" label="故障描述" min-width="150" show-overflow-tooltip />
      <el-table-column label="审核状态" min-width="100">
        <template #default="{ row }">
          <el-tag :type="getAuditStatusType(row.auditStatus)">
            {{ getAuditStatusText(row.auditStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="repairResult" label="维修结果" min-width="150" show-overflow-tooltip />
      <el-table-column label="是否报废" min-width="80">
        <template #default="{ row }">
          <el-tag :type="row.isScrapped ? 'danger' : 'success'">
            {{ row.isScrapped ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="报废审核状态" min-width="120">
        <template #default="{ row }">
          <el-tag v-if="row.isScrapped" :type="getAuditStatusType(row.scrapAuditStatus)">
            {{ getAuditStatusText(row.scrapAuditStatus) }}
          </el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" min-width="120" />
      <el-table-column label="操作" min-width="220">
        <template #default="{ row }">
          <!-- 普通操作人员可以修改、删除报修，以及填写维修结果和申请报废 -->
          <template v-if="isOperator">
            <el-button 
              v-if="row.auditStatus === 1 && !row.repairResult" 
              size="small" 
              type="primary" 
              @click="handleEditRepairResult(row)"
            >
              填写维修结果
            </el-button>
            <el-button 
              v-if="row.auditStatus === 1 && row.repairResult && !row.isScrapped" 
              size="small" 
              type="warning" 
              @click="handleApplyScrap(row)"
            >
              申请报废
            </el-button>
            <el-button 
              v-if="row.auditStatus === 0" 
              size="small" 
              type="primary" 
              @click="handleEditRepair(row)"
            >
              修改
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDeleteRepair(row.repairId)"
            >
              删除
            </el-button>
          </template>
          
          <!-- 部门经理可以审核报修和报废申请 -->
          <template v-if="isManager">
            <el-button 
              v-if="row.auditStatus === 0" 
              size="small" 
              type="primary" 
              @click="handleAuditRepair(row, 1)"
            >
              通过
            </el-button>
            <el-button 
              v-if="row.auditStatus === 0" 
              size="small" 
              type="danger" 
              @click="handleAuditRepair(row, 2)"
            >
              拒绝
            </el-button>
            <el-button 
              v-if="row.isScrapped && row.scrapAuditStatus === 0" 
              size="small" 
              type="primary" 
              @click="handleAuditScrap(row, 1)"
            >
              同意报废
            </el-button>
            <el-button 
              v-if="row.isScrapped && row.scrapAuditStatus === 0" 
              size="small" 
              type="danger" 
              @click="handleAuditScrap(row, 2)"
            >
              拒绝报废
            </el-button>
          </template>
          
          <!-- 系统管理员可以删除报修 -->
          <template v-if="isAdmin && !isOperator && !isManager">
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDeleteRepair(row.repairId)"
            >
              删除
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      background
      layout="prev, pager, next, jumper, ->, total"
      :total="pagination.total"
      :page-size="pagination.size"
      :current-page="pagination.current"
      @current-change="handlePageChange"
    />

    <!-- 新增/修改报修对话框 -->
    <el-dialog :title="editRepairId ? '修改报修' : '新增报修'" v-model="showAddDialog">
      <el-form :model="addForm" label-width="100px" :rules="formRules" ref="repairFormRef">
        <el-form-item label="设备编号" prop="deviceId">
          <el-select v-model="addForm.deviceId" placeholder="请选择设备" filterable>
            <el-option 
              v-for="device in deviceList" 
              :key="device.deviceId" 
              :label="`${device.deviceId} - ${device.deviceName}`" 
              :value="device.deviceId" 
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="部门" prop="deptId">
          <el-select v-model="addForm.deptId" placeholder="请选择部门">
            <el-option 
              v-for="dept in deptList" 
              :key="dept.deptId" 
              :label="dept.deptName" 
              :value="dept.deptId" 
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="故障描述" prop="faultDescription">
          <el-input v-model="addForm.faultDescription" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false; editRepairId = null">取消</el-button>
        <el-button type="primary" @click="handleSubmitRepair">确定</el-button>
      </template>
    </el-dialog>

    <!-- 填写维修结果对话框 -->
    <el-dialog title="填写维修结果" v-model="showRepairResultDialog">
      <el-form :model="repairResultForm" label-width="100px" :rules="repairResultRules" ref="repairResultFormRef">
        <el-form-item label="维修结果" prop="repairResult">
          <el-input v-model="repairResultForm.repairResult" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showRepairResultDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitRepairResult">确定</el-button>
      </template>
    </el-dialog>

    <!-- 申请报废对话框 -->
    <el-dialog title="申请报废" v-model="showScrapDialog">
      <p>确认申请报废该设备吗？</p>
      <template #footer>
        <el-button @click="showScrapDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitScrap">确定</el-button>
      </template>
    </el-dialog>

    <!-- 拒绝报废对话框 -->
    <el-dialog title="拒绝报废" v-model="showRejectScrapDialog">
      <el-form :model="rejectScrapForm" label-width="100px" :rules="rejectScrapRules" ref="rejectScrapFormRef">
        <el-form-item label="审核意见" prop="auditComment">
          <el-input v-model="rejectScrapForm.auditComment" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="维修方案" prop="repairPlan">
          <el-input v-model="rejectScrapForm.repairPlan" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showRejectScrapDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitRejectScrap">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, FormInstance } from 'element-plus'
import axios from 'axios'
import { useUserStore } from '@/stores/user'

// 从Pinia获取用户信息
const userStore = useUserStore()
const userTitle = computed(() => userStore.userInfo?.title || '')
const userDeptId = computed(() => userStore.userInfo?.deptId || null)

// 根据用户职称判断权限
const isOperator = computed(() => userTitle.value === '普通操作人员')
const isManager = computed(() => userTitle.value === '部门经理')
const isAdmin = computed(() => userTitle.value === '系统管理员')

// 查询表单
const searchForm = reactive({
  repairId: '',
  deviceId: '',
  deptId: '',
  faultDescription: '',
  auditStatus: '',
  repairResult: '',
  isScrapped: '',
  scrapAuditStatus: '',
  createTimeRange: [],
})

// 新增/修改表单
const addForm = reactive({
  deviceId: null,
  deptId: userDeptId,
  faultDescription: '',
  auditStatus: 0,
  repairResult: '',
  isScrapped: false,
  scrapAuditStatus: 0,
  auditComment: '',
  repairPlan: ''
})

// 维修结果表单
const repairResultForm = reactive({
  repairId: null,
  repairResult: ''
})

// 拒绝报废表单
const rejectScrapForm = reactive({
  repairId: null,
  auditComment: '',
  repairPlan: ''
})

// 表单验证规则
const formRules = reactive({
  deviceId: [{ required: true, message: '请选择设备', trigger: 'change' }],
  deptId: [{ required: true, message: '请选择部门', trigger: 'change' }],
  faultDescription: [{ required: true, message: '请输入故障描述', trigger: 'blur' }]
})

const repairResultRules = reactive({
  repairResult: [{ required: true, message: '请输入维修结果', trigger: 'blur' }]
})

const rejectScrapRules = reactive({
  auditComment: [{ required: true, message: '请输入审核意见', trigger: 'blur' }],
  repairPlan: [{ required: true, message: '请输入维修方案', trigger: 'blur' }]
})

// 数据列表
const repairList = ref([])
const deviceList = ref([])
const deptList = ref([])

// 分页信息
const pagination = reactive({
  total: 0,
  size: 10,
  current: 1
})

// 对话框控制
const showAddDialog = ref(false)
const showRepairResultDialog = ref(false)
const showScrapDialog = ref(false)
const showRejectScrapDialog = ref(false)
const editRepairId = ref<number | null>(null)
const currentRepair = ref<any>(null)

// 表单引用
const repairFormRef = ref<FormInstance | null>(null)
const repairResultFormRef = ref<FormInstance | null>(null)
const rejectScrapFormRef = ref<FormInstance | null>(null)

// 获取报修列表
const fetchRepairs = async (pageNum = 1) => {
  try {
    const params = {
      repairId: searchForm.repairId || null,
      deviceId: searchForm.deviceId || null,
      deptId: userDeptId.value,
      // deptId: searchForm.deptId || null,
      faultDescription: searchForm.faultDescription || null,
      auditStatus: searchForm.auditStatus !== '' ? searchForm.auditStatus : null,
      repairResult: searchForm.repairResult || null,
      isScrapped: searchForm.isScrapped !== '' ? searchForm.isScrapped : null,
      scrapAuditStatus: searchForm.scrapAuditStatus !== '' ? searchForm.scrapAuditStatus : null,
      createStartTime: searchForm.createTimeRange?.[0] || null,
      createEndTime: searchForm.createTimeRange?.[1] || null
    }
    const res = await axios.post(
      import.meta.env.VITE_API_URL + `repair/page?pageNum=${pageNum}&pageSize=${pagination.size}`,
      params
    )
    repairList.value = res.data.records
    pagination.total = res.data.total
    pagination.current = res.data.current
    pagination.size = res.data.size
  } catch (e) {
    ElMessage.error('获取报修数据失败')
  }
}

// 获取设备列表
const fetchDevices = async () => {
  try {
    const res = await axios.post(
      import.meta.env.VITE_API_URL + 'device/page?pageNum=1&pageSize=1000',
      {}
    )
    deviceList.value = res.data.records
  } catch (e) {
    ElMessage.error('获取设备数据失败')
  }
}

// 获取部门列表
const fetchDepts = async () => {
  try {
    const res = await axios.get(
      import.meta.env.VITE_API_URL + 'dept/list',
    )
    deptList.value = res.data.map(dept => ({
      deptId: dept.id,
      deptName: dept.deptName
    }))
  } catch (e) {
    ElMessage.error('获取部门数据失败')
  }
}

// 查询
const handleSearch = () => {
  fetchRepairs(1)
}

// 重置查询
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    // @ts-ignore
    searchForm[key] = ''
  })
  searchForm.createTimeRange = []
  fetchRepairs(1)
}

// 分页切换
const handlePageChange = (page: number) => {
  fetchRepairs(page)
}

// 获取审核状态文本
const getAuditStatusText = (status: number) => {
  const statusMap: Record<number, string> = {
    0: '待审核',
    1: '已通过',
    2: '已拒绝'
  }
  return statusMap[status] || '未知'
}

// 获取审核状态类型
const getAuditStatusType = (status: number) => {
  const typeMap: Record<number, string> = {
    0: 'warning',
    1: 'success',
    2: 'danger'
  }
  return typeMap[status] || 'info'
}

// 修改报修
const handleEditRepair = (row: any) => {
  Object.assign(addForm, {
    deviceId: row.deviceId,
    deptId: row.deptId,
    faultDescription: row.faultDescription,
    auditStatus: row.auditStatus,
    repairResult: row.repairResult,
    isScrapped: row.isScrapped,
    scrapAuditStatus: row.scrapAuditStatus,
    auditComment: row.auditComment,
    repairPlan: row.repairPlan
  })
  editRepairId.value = row.repairId
  showAddDialog.value = true
}

// 删除报修
const handleDeleteRepair = async (repairId: number) => {
  try {
    await axios.delete(import.meta.env.VITE_API_URL + `repair/${repairId}`)
    ElMessage.success('删除成功')
    fetchRepairs(pagination.current)
  } catch (e) {
    ElMessage.error('删除失败')
  }
}

// 提交报修
const handleSubmitRepair = async () => {
  if (!repairFormRef.value) return
  
  await repairFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (editRepairId.value) {
          // 修改
          await axios.put(import.meta.env.VITE_API_URL + 'repair/update', {
            repairId: editRepairId.value,
            ...addForm
          })
          ElMessage.success('修改成功')
        } else {
          // 新增
          await axios.post(import.meta.env.VITE_API_URL + 'repair/add', addForm)
          ElMessage.success('添加成功')
        }
        showAddDialog.value = false
        editRepairId.value = null
        resetAddForm()
        fetchRepairs(1)
      } catch (e) {
        ElMessage.error(editRepairId.value ? '修改失败' : '添加失败')
      }
    }
  })
}

// 重置添加表单
const resetAddForm = () => {
  Object.assign(addForm, {
    deviceId: null,
    deptId: userDeptId,
    faultDescription: '',
    auditStatus: 0,
    repairResult: '',
    isScrapped: false,
    scrapAuditStatus: 0,
    auditComment: '',
    repairPlan: ''
  })
}

// 审核报修
const handleAuditRepair = async (row: any, status: number) => {
  try {
    await axios.put(import.meta.env.VITE_API_URL + 'repair/update', {
      repairId: row.repairId,
      auditStatus: status
    })
    ElMessage.success('审核成功')
    fetchRepairs(pagination.current)
  } catch (e) {
    ElMessage.error('审核失败')
  }
}

// 填写维修结果
const handleEditRepairResult = (row: any) => {
  repairResultForm.repairId = row.repairId
  repairResultForm.repairResult = row.repairResult || ''
  showRepairResultDialog.value = true
}

// 提交维修结果
const handleSubmitRepairResult = async () => {
  if (!repairResultFormRef.value) return
  
  await repairResultFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await axios.put(import.meta.env.VITE_API_URL + 'repair/update', {
          repairId: repairResultForm.repairId,
          repairResult: repairResultForm.repairResult
        })
        ElMessage.success('提交成功')
        showRepairResultDialog.value = false
        fetchRepairs(pagination.current)
      } catch (e) {
        ElMessage.error('提交失败')
      }
    }
  })
}

// 申请报废
const handleApplyScrap = (row: any) => {
  currentRepair.value = row
  showScrapDialog.value = true
}

// 提交报废申请
const handleSubmitScrap = async () => {
  try {
    await axios.put(import.meta.env.VITE_API_URL + 'repair/update', {
      repairId: currentRepair.value.repairId,
      isScrapped: true,
      scrapAuditStatus: 0
    })
    ElMessage.success('申请报废成功')
    showScrapDialog.value = false
    fetchRepairs(pagination.current)
  } catch (e) {
    ElMessage.error('申请报废失败')
  }
}

// 审核报废
const handleAuditScrap = async (row: any, status: number) => {
  if (status === 2) {
    // 拒绝报废，需要填写意见和维修方案
    rejectScrapForm.repairId = row.repairId
    rejectScrapForm.auditComment = ''
    rejectScrapForm.repairPlan = ''
    showRejectScrapDialog.value = true
  } else {
    // 同意报废
    try {
      await axios.get(import.meta.env.VITE_API_URL + 'repair/scrapAudit', {
        params: {
          repairId: row.repairId,
          audit: status,
          auditComment: '',
          repairPlan: ''
        }
      })
      ElMessage.success('报废审核完成')
      fetchRepairs(pagination.current)
    } catch (e) {
      ElMessage.error('报废审核失败')
    }
  }
}

// 提交拒绝报废
const handleSubmitRejectScrap = async () => {
  if (!rejectScrapFormRef.value) return
  
  await rejectScrapFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await axios.get(import.meta.env.VITE_API_URL + 'repair/scrapAudit', {
          params: {
            repairId: rejectScrapForm.repairId,
            audit: 2,
            auditComment: rejectScrapForm.auditComment,
            repairPlan: rejectScrapForm.repairPlan
          }
        })
        ElMessage.success('报废审核完成')
        showRejectScrapDialog.value = false
        fetchRepairs(pagination.current)
      } catch (e) {
        ElMessage.error('报废审核失败')
      }
    }
  })
}

// 初始化
onMounted(() => {
  fetchRepairs()
  fetchDevices()
  fetchDepts()
})
</script>

<style scoped>
.repair-manage {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.search-form {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}
</style>